package cn.ictgu.parse;

import cn.ictgu.dto.VideoInfo;
import cn.ictgu.parse.crawler.Iqiyi;
import cn.ictgu.parse.crawler.Letv;
import cn.ictgu.parse.crawler.Mgtv;
import cn.ictgu.parse.crawler.Qq;
import cn.ictgu.parse.crawler.Sohu;
import cn.ictgu.parse.crawler.Youku;
import cn.ictgu.tools.UrlUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 解析器
 * Created by Silence on 2017/1/5.
 */
@Component
@Log4j
public class ParseManager {

  @Autowired
  private StringRedisTemplate redisTemplate;

  private Map<String, VideoParse> videoParseMap;

  public ParseManager(){
    videoParseMap = new HashMap<>();
    videoParseMap.put("iqiyi.com", new Iqiyi());
    videoParseMap.put("le.com", new Letv());
    videoParseMap.put("mgtv.com", new Mgtv());
    videoParseMap.put("sohu.com", new Sohu());
    videoParseMap.put("youku.com", new Youku());
    videoParseMap.put("qq.com", new Qq());
  }

  public VideoParse getVideoParse(String key){
    return videoParseMap.get(key);
  }

  public VideoInfo parseVideo(String url){
    String cacheValue = redisTemplate.opsForValue().get(url);
    VideoInfo videoInfo;
    if (StringUtils.isEmpty(cacheValue)){
      log.info("开始解析：" + url);
      String key = UrlUtils.getTopDomain(url);
      VideoParse videoParse = this.getVideoParse(key);
      videoInfo = videoParse.parseVideoFromUrl(url);
      this.cacheVideoInfo(url, videoInfo);
    }else {
      log.info("开始获取缓存信息：" + url);
      videoInfo = JSONObject.parseObject(cacheValue, VideoInfo.class);
    }
    return videoInfo;
  }

  @Async
  private void cacheVideoInfo(String url, VideoInfo videoInfo){
    log.info("缓存视频：" + url);
    String value = JSONObject.toJSONString(videoInfo);
    redisTemplate.opsForValue().set(url, value);
    redisTemplate.expire(url, 3, TimeUnit.HOURS);
  }

}
